package common

import (
	"errors"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	translation "github.com/go-playground/validator/v10/translations/zh"
)

type ValidTrans struct {
	trans ut.Translator
}

//初始化
func (v *ValidTrans) TranslatorInit() {
	v.trans, _ = ut.New(zh.New()).GetTranslator("zh")

	translation.RegisterDefaultTranslations(binding.Validator.Engine().(*validator.Validate), v.trans)
}

//返回错误信息
func (v *ValidTrans) TranslateErr(err error) error {
	if validationErrors, ok := err.(validator.ValidationErrors); !ok {
		return err
	} else {
		for _, e := range validationErrors {
			return errors.New(e.Translate(v.trans))
		}
	}
	return err
}
